package org.hako.recite.word.parser.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.hako.recite.word.model.Word;
import org.hako.recite.word.parser.WordList;
import org.hako.recite.word.parser.WordListParseException;
import org.hako.recite.word.util.StringUtils;

/**
 * Parse word list from text file.
 * 
 * @author xnnyygn
 */
public class TextFileWordListParser extends AbstractWordListParser {

	@Override
	public WordList parse(InputStream inputStream)
			throws WordListParseException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream));
		WordList wordList = new WordList();
		String line = null;
		int lineIndex = 0;
		try {
			while ((line = reader.readLine()) != null) {
				if (StringUtils.isBlank(line)) {
					continue;
				}
				String[] cells = line.split("\\s");
				if (lineIndex == 0) {
					wordList.setColumnTitles(cells);
				} else {
					if (cells.length != wordList.getColumnCount()) {
						throw new WordListParseException(
								"Count of word fields not equal to "
										+ "column titles count");
					}
					wordList.addWord(new Word(cells));
				}
				lineIndex++;
			}
			return wordList;
		} catch (IOException e) {
			throw new WordListParseException(e);
		}
	}
}
